<?php

namespace App\Http\Controllers\Admin\UserManager;

use App\Enums\ExportEnum;
use App\Jobs\QiPao\ExcelJob;
use App\Services\Tools\Export;
use App\Exceptions\BasicException;
use Illuminate\Support\Facades\DB;
use App\Http\Controllers\BaseController;
use App\Services\Tools\ExportService;
use App\Services\Tools\HelperService;
use Illuminate\Http\Request;

//引用http请求类
use App\Response\Response;
use Illuminate\Support\Facades\Validator;
use App\Repositories\RoomAccountRepository;

class UserAccountLogController extends BaseController
{
    /**
     * @api {get} /user-manager/user-account-log 用户收支日志列表
     * @apiVersion 0.1.0
     * @apiName 会员管理-用户收支日志列表
     * @apiGroup 会员管理
     * @apiParam {number} account_type 账户类型，1：余额；2：收益，必须
     * @apiParam {string} happen_time_start 开始时间（y-m-d h:i:s，下同）
     * @apiParam {string} happen_time_end 结束时间
     * @apiParam {number} change_type 变动类型，0(默认)：不限制；其它根据接口获取
     * @apiParam {string} mobile 用户手机号
     * @apiParam {number} user_code 用户编号
     * @apiParam {string} nickname 用户昵称
     * @apiParam {number} page 当前页数 可选
     * @apiParam {number} perPage 分页容量 可选
     * @apiSuccessExample 成功响应
     * {
    "code": 200,
    "data": {
    "current_page": 1,
    "data": [
    {
    "id": 226242,
    "user_id": 14,
    "change_money": "116666.20",
    "change_type": 16,
    "change_desc": "收到 小气泡2375945 凤凰涅槃",
    "created_at": "2021-12-27 13:53:13",
    "change_type_name": "收益增加",
    "mobile": "18906514971",
    "user_code": 3644972,
    "nickname": "小气泡3644972"
    }
    ],
    "first_page_url": "http://qh-admin-api/user-manager/user-account-log?page=1",
    "from": 1,
    "last_page": 12,
    "last_page_url": "http://qh-admin-api/user-manager/user-account-log?page=12",
    "next_page_url": "http://qh-admin-api/user-manager/user-account-log?page=2",
    "path": "http://qh-admin-api/user-manager/user-account-log",
    "per_page": "1",
    "prev_page_url": null,
    "to": 1,
    "total": 12,
    "sum_coin": "请选择类别"
    },
    "message": ""
    }
     */
    public function list(Request $request)
    {
        $params = $request->only('account_type', 'happen_time_start', 'happen_time_end', 'change_type', 'mobile', 'user_code', 'nickname', 'page', 'perPage');
        //参数校验
        $validator = Validator::make($params, [
            'account_type' => 'required||integer|in:1,2',
            'change_type' => 'filled|integer|min:0',
            'perPage' => 'filled|numeric',
            'page' => 'filled|numeric',
            'happen_time_start' => 'date_format:Y-m-d H:i:s',
            'happen_time_end'   => 'date_format:Y-m-d H:i:s',
        ]);
        if ($validator->fails()) {
            throw new BasicException(10001, $validator->errors()->first());
        }

        $list = app('repo_account_log')->getUserAccountLog($params);

        return Response::sendData($list);
    }

    /**
     * @api {get} /user-manager/user-account-log/export/excel 用户收支日志-导出
     * @apiVersion 0.1.0
     * @apiName  会员管理-用户收支日志-导出
     * @apiGroup 会员管理
     * @apiParam {number} change_type 当前页数 可选
     * @apiParam {string} mobile 当前页数 可选
     * @apiParam {string} nickname 当前页数 可选
     * @apiParam {number} user_code 当前页数 可选
     * @apiParam {number} page 当前页数 可选
     * @apiParam {number} perPage 分页容量 可选
     * @apiSuccessExample 成功响应
     * {
     * "code": 200,
     * "data": {
     * "download_url": "asdasdasd.com"
     * }
     */
    public function export(Request $request)
    {
        //参数校验
        try {
            $this->validate($request, [
                'account_type' => 'required||integer|in:1,2,3',
                'change_type'       => 'filled|numeric',
                'mobile'            => 'filled|string',
                'nickname'          => 'filled|string',
                'user_code'         => 'filled|numeric',
                'happen_time_start' => 'required_with:happen_time_end|date_format:Y-m-d H:i:s',
                'happen_time_end'   => 'required_with:happen_time_start|date_format:Y-m-d H:i:s',
            ]);
        } catch (\Exception $e) {
            throw new BasicException(10001, json_encode($e->errors()));
        }

        ini_set('memory_limit', '2048M');

        $params = $request->input();
        $list = app('repo_account_log')->getUserAccountLogQueryList($params);//dd($list);

        //        if ($list){
        //            foreach ($list as $item) {
        //                //处理昵称中的emoji表情，防止导出excel错误
        //                $nickname = HelperService::wxNickNameFormat($item['nickname']);
        //                $result[] = [
        //                    $item['id'],
        //                    $item['user_code'],
        //                    $nickname,
        //                    $item['mobile'],
        //                    $item['user_money'],
        //                    $item['change_type_name'],
        //                    $item['change_desc'],
        //                    $item['change_time'],
        //                ];
        //            }
        //        }
        //        if (empty($result)) {
        //            throw new BasicException(0, '没有结果');
        //        }
        //        $headings = [
        //            '序号',
        //            '用户编号',
        //            '昵称',
        //            '手机',
        //            '金币数量',
        //            '类别',
        //            '备注',
        //            '时间',
        //        ];

        //        return app('repo_export')->export(18, $request->all(), $headings, $result);

        $fields = [
            ['field' => 'id', 'header' => '序号', 'width' => '18'],
            ['field' => 'user_code', 'header' => '用户编号', 'width' => '18'],
            ['field' => 'nickname', 'header' => '用户昵称', 'width' => '18'],
            ['field' => 'mobile', 'header' => '手机号', 'width' => '18'],
            ['field' => 'user_money', 'header' => '金币数量', 'width' => '18'],
            ['field' => 'change_type_name', 'header' => '类别', 'width' => '18'],
            ['field' => 'change_desc', 'header' => '备注', 'width' => '50'],
            ['field' => 'change_time', 'header' => '时间', 'width' => '18'],
        ];
        $downloadUrl = Export::exportUsePhpOffice('user_account_log', $fields, $list);

        //记录日志
        app('model_admin_export_log')->add(18, $params, $downloadUrl);

        return Response::sendData(['download_url' => $downloadUrl]);
    }


    /**
     * @api {get} /user-manager/user-account-log/export/excel/async 异步用户收支日志-导出
     * @apiVersion 0.1.0
     * @apiName  会员管理-异步用户收支日志-导出
     * @apiGroup 会员管理
     * @apiParam {number} account_type 账户类型，1：余额；2：收益，必须
     * @apiParam {number} change_type 当前页数 可选
     * @apiParam {string} mobile 当前页数 可选
     * @apiParam {string} nickname 当前页数 可选
     * @apiParam {number} user_code 当前页数 可选
     * @apiParam {number} page 当前页数 可选
     * @apiParam {number} perPage 分页容量 可选
     * @apiSuccessExample 成功响应
     * {
     * "code": 200,
     * "data": {
     * "download_url": "asdasdasd.com"
     * }
     */
    public function asyncToExcel(Request $request)
    {
        //参数校验
        try {
            $this->validate($request, [
                'account_type' => 'filled|integer|in:1,2,3',
                'change_type'       => 'filled|numeric',
                'mobile'            => 'filled|string',
                'nickname'          => 'filled|string',
                'user_code'         => 'filled|numeric',
                'happen_time_start' => 'required_with:happen_time_end|date_format:Y-m-d H:i:s',
                'happen_time_end'   => 'required_with:happen_time_start|date_format:Y-m-d H:i:s',
            ]);
        } catch (\Exception $e) {
            throw new BasicException(10001, json_encode($e->errors()));
        }

        $params = $request->only(['account_type', 'change_type', 'nickname', 'mobile', 'user_code', 'happen_time_start', 'happen_time_end']);

        $data = [
            'admin_id'     => $request->admin_id ?? '',
            'data_no'      => 18, //ExportEnum::NO
            'condition'    => json_encode($params) ?? '',
            'status'       => 0, //正在导出
            'title'        => '用户收支日志 异步导出', //正在导出
            'download_url' => '',
        ];
        $exportLogId = app('model_admin_export_log')->insertGetId($data);
        $excel = new ExcelJob($exportLogId, $request->admin_id, 18, $params);
        // 标记导出程序开始运行
        dispatch($excel)->onQueue(env('RABBITMQ_QUEUE_EXCEL'));  //推送到指定队列
        return Response::sendData('', '请等待');
    }

    /**
     * @api {get} /user-manager/user-account-log/change-type/list 用户收支类型列表
     * @apiVersion 0.1.0
     * @apiName 会员管理-用户收支类型列表
     * @apiGroup 会员管理
     * @apiSuccessExample 成功响应
     * {
     * "code": 200,
     * "data": [
     * {
     * "change_type": 1,
     * "name": "充值"
     * }
     * ]
     * }
     */
    public function typeList(Request $request)
    {
        $list = app('repo_account_log')->typeList();
        return Response::sendData($list);
    }

    /**
     * @api {get} /user-manager/user-account-log/earningsFreeze 账户收益冻结日志
     * @apiVersion 0.1.0
     * @apiName 用户管理-账户收益冻结日志
     * @apiGroup 用户管理
     * @apiSuccessExample 成功响应
     * {
     * "code": 200,
     * "data": {
     * "current_page": 1,
     * "data": [
     * {
     * "log_id": 13, 序号
     * "admin_id": 73,
     * "user_id": 1296021,
     * "client_ip": "127.0.0.1", ip
     * "content": "冻结用户的账户收益，原因：不解释", 操作内容
     * "add_time": "2021-06-29 10:00:44", 发生时间
     * "admin_name": "xlb", 管理员
     * "user_code": 7156912, 用户ID
     * "nickname": "" 用户昵称
     * }
     * ],
     * "first_page_url": "http://local.qipaoadmin/user-manager/user-account-log/earningsFreeze?page=1",
     * "from": 1,
     * "last_page": 1,
     * "last_page_url": "http://local.qipaoadmin/user-manager/user-account-log/earningsFreeze?page=1",
     * "next_page_url": null,
     * "path": "http://local.qipaoadmin/user-manager/user-account-log/earningsFreeze",
     * "per_page": 10,
     * "prev_page_url": null,
     * "to": 4,
     * "total": 4
     * }
     * }
     */
    public function earningsFreeze(Request $request)
    {
        //参数校验
        $v = app('validator')->make(
            $request->all(),
            [
                'user_code' => 'integer',
                'page'      => 'integer',
                'page_size' => 'integer',
                'content'   => 'string|max:255',
                'type'      => 'integer',
            ]
        );
        if ($v->fails()) {
            throw new BasicException(10001, $v->errors()->first());
        }
        $userCode = $request->user_code;
        $content = $request->input('content', '');
        $pageSize = $request->page_size ?: 10;
        $type = $request->input('type', 0);


        $where = [];
        if ($userCode) {
            $user = app('model_user_data')->select('user_id')->where(['user_code' => $userCode])->first();
            if ($user) {
                $where['user_id'] = $user->user_id;
            } else {
                $where['user_id'] = 0;
            }
        }
        if (strlen($content) != 0) {
            $where[] = ['content', 'like', '%' . $content . '%'];
        }
        if (!empty($type)) {
            $where[] = ['type', '=', $type];
        }


        $list = app('model_user_earnings_freeze_log')
            ->select('log_id', 'admin_id', 'user_id', 'client_ip', 'content', 'add_time','type')
            ->where($where)
            ->orderBy('log_id','desc')
            ->paginate($pageSize)->toArray();
        $userIds = array_column($list['data'], 'user_id');
        $userIds = array_unique($userIds);
        $adminIds = array_column($list['data'], 'admin_id');
        $adminIds = array_unique($adminIds);

        $users = app('model_user_data')
            ->select('user_id', 'user_code', 'nickname')
            ->whereIn('user_id', $userIds)
            ->get()->toArray();
        $users = array_column($users, null, 'user_id');
        $admins = app('model_admin')->whereIn('admin_id', $adminIds)->pluck('admin_name', 'admin_id');

        foreach ($list['data'] as &$v) {
            if (isset($admins[$v['admin_id']])) {
                $v['admin_name'] = $admins[$v['admin_id']];
            } else {
                $v['admin_name'] = '';
            }
            if (isset($users[$v['user_id']])) {
                $v['user_code'] = $users[$v['user_id']]['user_code'];
                $v['nickname'] = $users[$v['user_id']]['nickname'];
            } else {
                $v['user_code'] = '';
                $v['nickname'] = '';
            }
            $v['add_time'] = date('Y-m-d H:i:s', $v['add_time']);

            //拆分原因
            $contentArr = explode("，原因：", $v['content']);
            $v['content_type'] = $contentArr[0] ?? '';
            $v['content_reason'] = $contentArr[1] ?? '';
        }

        return Response::sendData($list);
    }

    public function alllist(Request $request)
    {
        $params = $request->only('happen_time_start', 'happen_time_end', 'change_type', 'mobile', 'user_code', 'nickname', 'page', 'perPage', 'page_type', 'page_info', 'page_pre_info');
        //参数校验
        $validator = Validator::make($params, [
            'perPage' => 'filled|numeric',
            'page' => 'filled|numeric',
            'happen_time_start' => 'date_format:Y-m-d H:i:s',
            'happen_time_end'   => 'date_format:Y-m-d H:i:s',
        ]);
        if ($validator->fails()) {
            throw new BasicException(10001, $validator->errors()->first());
        }

        $list = app('repo_account_log')->getAllUserAccountLog($params);

        return Response::sendData($list);
    }
}
